const jimp = require('jimp');
const fs = require('fs');
const _ = require('lodash');

module.exports = app => {
    class Controller extends app.Controller {
        async receive() {
            const {anchor_id, platform_id, schedule_id, buffer} = this.ctx.args[0];
            const now = new Date();
            const fileName = now.getTime();
            const filePath = app.config.screenshot.path + '/' + fileName;
            const thumbnailPath = app.config.screenshot.path + '/' + fileName + '_small';

            jimp.read(buffer).then(lenna => {
                // lenna.scale(0.25).quality(50).write(thumbnailPath);
                // console.log('写入缩略图 1', thumbnailPath);
                lenna.scale(0.25).quality(50).getBuffer(jimp.MIME_JPEG, (err, buffer) => {
                    // console.log('写入缩略图 2', err);
                    saveFile(thumbnailPath, buffer);
                });
            });
            saveFile(filePath, buffer);
            let file = await app.model.File.create({file: fileName, created_at: now});
            _.each(schedule_id, id => {
                app.model.DetailScheduleImage.create({file_id: file.id, platform_id, anchor_id, schedule_id: id});
            });
        }

        async taskLength() {
            const {ctx, app} = this;
            const socket = ctx.socket;
            const {wait, success, fail} = this.ctx.args[0];
            let redisKey = app.config.screenshot.redisClientKey + socket.id;
            let data = await app.redis.get(redisKey);
            if (!data)
                return;
            data = JSON.parse(data);
            data.wait = wait;
            data.success = success;
            data.fail = fail;
            app.redis.set(redisKey, JSON.stringify(data));
        }
    }

    return Controller;
};

function saveFile(path, buffer) {
    return new Promise(resolve => {
        fs.writeFile(path, buffer, (err) => {
            if (err) throw err;
            resolve();
        });
    });
}